package cn.itcast.hotel;

import cn.itcast.hotel.constants.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class EsIndexDemo {

    private RestHighLevelClient client;


    @BeforeEach
    void setUp() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.19.99:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }


    @Test
    public void creatIndex() throws IOException {
        //创建Request对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //请求参数 MAPPING_TEMPLATE是静态常量字符串，内容是创建索引库的DSL语句
        request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);

        //发起请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);

        boolean b = response.isAcknowledged();

        System.out.println("创建索引库结果"+b);
    }

    @Test
    void testDeleteHotelIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);

        boolean b = response.isAcknowledged();
        System.out.println("删除索引库结果"+b);
    }


    @Test
    void testExistsHotelIndex() throws IOException {
        // 1.创建Request对象
        GetIndexRequest request = new GetIndexRequest("hotel");
        // 2.发送请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        // 3.输出
        System.err.println(exists ? "索引库已经存在！" : "索引库不存在！");
    }
}
